{#if}

Posted on 2023-02-07 by

henrikvilhelmberglund

The if block {#if} allows us to show or hide content based on a certain condition.

To start the if block we start with curly brackets {} , inside of them type # and then if . Next we type the condition condition1 .

To close the if block we start with curly brackets again and inside type /if .

We can also have else and else if in our if blocks.

Just type {:else} or {:else if} inside the if block.


Both conditions are true!

App.svelte

<script>
	let condition1 = true;
	let condition2 = true;

	function toggleCondition1(params) {
		condition1 = !condition1;
	}
	function toggleCondition2(params) {
		condition2 = !condition2;
	}
	function check(condition1, condition2) {
		return condition1 || condition2;
	}
</script>

<button on:click={toggleCondition1}>Condition 1: {condition1}</button>
<button on:click={toggleCondition2}>Condition 2: {condition2}</button>

<hr class="w-full p-0" />

{#if condition1 && condition2}
	Both conditions are true!
	<!-- we can use any javascript code in here, like a function -->
{:else if check(condition1, condition2)}
	Either condition1 or condition2 is true.
{:else}
	Both conditions are false.
{/if}

        

If the condition is true the contents of the if block will be shown .

The logic block pattern

Other logic blocks in Svelte follow the above pattern.

First insert curly braces so we can type code, after that we start the block with # , we continue the block with : and we exit the block with / .

We can also nest logic blocks just like in Javascript.